package com.education.project.web.controller;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.education.project.model.WebUser;
import com.education.project.service.WebUserService;
import com.education.project.web.form.WebUserLoginForm;

@Controller
public class IndexController {
	@Autowired
	private WebUserService webUserService;
	
	@GetMapping("/login")
	public ModelAndView getLoginPage() {
		ModelAndView model = new ModelAndView("login");
		model.addObject("form", new WebUserLoginForm());
		return model;
	}
	
	@PostMapping("/login")
	public String login(
			@Valid @ModelAttribute("form") WebUserLoginForm form,
			BindingResult binder,
			HttpSession session) {
		WebUser webUser = null;
		if(!binder.hasErrors()) {
			webUser = webUserService.login(form.getUsername(), form.getPassword());
			if(webUser==null) {
				binder.rejectValue("username", "error", "用户名或密码错误");
			}
		}
		if(binder.hasErrors()) {
			return "login";
		}
		session.setAttribute("webUser", webUser);
		return "redirect:/user/index";
	}
	
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/login";
	}
}
